package com.project.myproject.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Honorable(mabingqian)
 * @description
 * @date 2020/8/3 11:41
 * @update （更新、优化，注明点）
 */
public class NettyDemo {

    public static void main(String[] args) {
        NioEventLoopGroup boosGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        final EventExecutorGroup bussinessGroup = new DefaultEventExecutorGroup(10);
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(workGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.SO_BACKLOG, 100)
                .childAttr(AttributeKey.newInstance("clientKey"), "clientValue")
                .attr(AttributeKey.newInstance("serverName"), "nettyServer")
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel channel) throws Exception {
                        ChannelPipeline p = channel.pipeline();

                        p.addLast(bussinessGroup, new Bussiness());
                    }
                });

        ChannelFuture bind = serverBootstrap.bind(8083);
        if (bind.isSuccess()) {
            System.out.println("启动 Netty 成功");
        }
    }
}


@Slf4j
class Bussiness extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        log.info("{} : channelRegistered BusinessHandler", Thread.currentThread());
        super.channelRegistered(ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("{} : channelActive BusinessHandler", Thread.currentThread());
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("{} begin : channelRead BusinessHandler 模拟耗时业务逻辑", Thread.currentThread());
        Thread.sleep(3000);
        log.info("{} end : channelRead BusinessHandler 模拟耗时业务逻辑", Thread.currentThread());
        super.channelRead(ctx, msg);
    }
}
